var url = require('url');  
var queryString = require('querystring');  
var config = require('../config/config')
var crypto = require('crypto');  
var request = require('request');  
var xml2jsparseString = require('xml2js').parseString;  
var http = require('http');  
var md5 = require('md5');  
var cookParser = require('cookie-parser');  
var session = require('express-session');  
var express = require('express');  
var app = express();  
var UUID = require('uuid');
var xml2js = require('xml2js')
var log4 = require('../tools/logs')
var comment = require('./comment')

    exports.paySinsapi = function(req,res,next) {
        var ret = {  
            appId: config.appId,  
            timeStamp:comment.createTimeStamp(),
            nonceStr:comment.createNonceStr(),
            package:'prepay_id='+prepay_id,
            signType:"MD5"
        };  
        var string = comment.raw(ret); 
        var key = config.key 
        string = string + '&key=' + key; //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置  
        var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex'); 
        var signstr = sign.toUpperCase()
        ret.signed = signstr
        log4.logs('打印微信签名参数')
        log4.logs(ret)
        res.json({
            code:'200',
            data:ret
        }) 
        return;  
    }
    var prepay_id = '';
    exports.order = function (attach, body, mch_id, openid, total_fee, notify_url,spbill_create_ip,reqsss,ressss) {  
        log4.logs('进入下单接口')
        var nonce_str = comment.createNonceStr();  
        var timeStamp = comment.createTimeStamp();  
        var out_trade_no = 	Math.random().toString(26).substr(2);
        var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";  
        var appid = config.appId
        var formData = "<xml>";  
        formData += "<appid>" + appid + "</appid>"; //appid  
        formData += "<attach>" + attach + "</attach>"; //附加数据  
        formData += "<body>" + body + "</body>";  
        formData += "<mch_id>" + mch_id + "</mch_id>"; //商户号  
        formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串，不长于32位。  
        formData += "<notify_url>" + notify_url + "</notify_url>";  
        formData += "<openid>" + openid + "</openid>";  
        formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";  
        formData += "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>";  
        formData += "<total_fee>" + total_fee + "</total_fee>";  
        formData += "<trade_type>JSAPI</trade_type>";  
        formData += "<sign>" + comment.paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, 'JSAPI') + "</sign>";  
        formData += "</xml>";  
        log4.logs('打印下单入参')
        log4.logs(formData)
        request({
            url: url, 
            method: 'POST', 
            body: formData 
        },function(error,response,body){
            if (!error && response.statusCode == 200) {
                // 微信返回的数据为 xml 格式， 需要装换为 json 数据， 便于使用
                xml2jsparseString(body, {async:true}, function (error, result) {
                    prepay_id = result.xml.prepay_id[0]
                    log4.logs('打印出prepay_id'+prepay_id)
                    ressss.json({
                        'code':200,
                        'msg':'下单接口请求成功！',
                        'prepay_id':prepay_id
                    })
                    return;
                });
            } else {
                log4.logs('下单接口请求失败'+error)
                ressss.json({
                    'code':201,
                    'msg':'下单接口请求失败！'
                })
                return;
            }
        })
    }
    exports.searchOrder = function(req,res,next){
        var wxOrderCode = ''
        try{
            wxOrderCode = req.query.wxorder
        }catch(error){
            log4.logs(error)
        }
        const urlss = 'https://api.mch.weixin.qq.com/pay/orderquery'
        var formDatass = {
            appid:config.appId,
            mch_id:config.mch_id,
            nonce_str:comment.createNonceStr(),
            transaction_id:wxOrderCode,
        }
        let signs = comment.usualSign(formDatass)
        log4.logs('生成签名入参')
        log4.logs(formDatass)
        var formData = "<xml>"; 
        formData += "<appid>" + config.appId + "</appid>"; 
        formData += "<mch_id>" + config.mch_id + "</mch_id>";
        formData += "<nonce_str>" + formDatass.nonce_str + "</nonce_str>";
        formData += "<transaction_id>" + formDatass.transaction_id + "</transaction_id>";
        formData += "<sign>" + signs + "</sign>";
        formData += "</xml>";
        log4.logs('打印查询订单接口入参')
        log4.logs(formData)
        request({
            url: urlss, 
            method: 'POST', 
            body: formData 
        },function(error,response,body){
            if (!error && response.statusCode == 200) {
                // 微信返回的数据为 xml 格式， 需要装换为 json 数据， 便于使用
                xml2jsparseString(body, {async:true}, function (error, result) {
                    log4.logs('输出订单查询结果')
                    log4.logs(result.xml)
                    res.json({
                        'code':200,
                        'msg':'查询成功',
                        'data':result.xml
                    })
                    return;
                });
            } else {
                log4.logs('查询失败'+error)
                res.json({
                    'code':201,
                    'msg':'查询失败'
                })
                return;
            }
        })
    }
    exports.downloadbill = function(req,res,next){
        let searchListData = ''
        try{
            searchListData = req.query.searchListData 
        }catch(error){
            log4.logs(error)
        }
        var url = "https://api.mch.weixin.qq.com/pay/downloadbill"  
        var ret = {
            appid:config.appId,
            bill_date:searchListData,
            bill_type:'ALL',
            mch_id:config.mch_id,
            nonce_str:comment.createNonceStr()
        }
        var formData = "<xml>";  
        formData += "<appid>" + ret.appid + "</appid>"; //appid  
        formData += "<bill_date>" + ret.bill_date + "</bill_date>"; 
        formData += "<mch_id>" + ret.mch_id + "</mch_id>"; //商户号  
        formData += "<bill_type>" + ret.bill_type + "</bill_type>"; 
        formData += "<nonce_str>" + ret.nonce_str + "</nonce_str>"; 
        formData += "<sign>" + comment.usualSign(ret) + "</sign>";  
        formData += "</xml>";  
        log4.logs('打印查询兑账单入参')
        log4.logs(formData)
        request({
            url: url, 
            method: 'POST', 
            body: formData 
        },function(error,response,body){
            log4.logs('打印订单查询接口')
            log4.logs(response.body)
            res.json({
                code:200,
                msg:'访问成功',
                data:response.body
            })
        })
    }
    exports.Notice = function(req,res,next){
        let noticexml = req.body
        xml2jsparseString(noticexml, {async:true}, function (error, result) {
            log4.logs('打印支付报错信息')
            log4.logs(result.xml)
        });
    }
    